package serveurChatRMI.rmi.src;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Iterator;
import java.util.LinkedList;

import serveurChatRMI.rmi.interfaces.InterfaceSujetDiscussion;
import clientInterfaces.InterfaceAffichageClient;

public class SujetDiscussion extends UnicastRemoteObject implements InterfaceSujetDiscussion {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7614453979712289920L;
	private String name;
	private LinkedList<InterfaceAffichageClient> listClient;
	
	
	public SujetDiscussion(String name) throws RemoteException {
		this.name=name;
		listClient = new LinkedList<InterfaceAffichageClient>();
	}
	
	@Override
	public void inscription(InterfaceAffichageClient c) throws RemoteException {
		listClient.add(c);
		System.out.println("Nombre de client : "+listClient.size());
		
		Iterator<InterfaceAffichageClient> itr = listClient.iterator();
		while(itr.hasNext()) {
			InterfaceAffichageClient iac = itr.next();
			try {
				iac.updateListeClient(listClient);
			} catch (Exception e) {
				itr.remove();
			}
	       
		}
	}

	@Override
	public void desInscription(InterfaceAffichageClient c) throws RemoteException {
		listClient.remove(c);
		
		Iterator<InterfaceAffichageClient> itr = listClient.iterator();
		while(itr.hasNext()) {
			InterfaceAffichageClient iac = itr.next();
			try {
				iac.updateListeClient(listClient);
			} catch (Exception e) {
				itr.remove();
			}
	       
		}
	}

	
	/**
	 * Diffuse le message d'un client a tous les inscrits
	 * 
	 * pre-condition : etre inscrit au sujet
	 */
	@Override
	public void diffuse(String message, InterfaceAffichageClient c) throws RemoteException {
		
		if(listClient.contains(c)) {
		
			System.out.println("Nouveau message de "+c.getName()+" : "+message);
			
			Iterator<InterfaceAffichageClient> itr = listClient.iterator();
			
			while(itr.hasNext()) {
				InterfaceAffichageClient iac = itr.next();
				try {
					iac.afficheMessage(c.getName()+" : "+message);
				} catch(RemoteException re) {
					//Si un client ne repond pas, on le supprime de la liste des abonnes
					itr.remove();
					this.desInscription(iac);
				}
		       
			}
		}
		else {
			c.afficheMessage("Vous n'etes pas inscrit a ce sujet");
		}
	}

	@Override
	public String getName() throws RemoteException {
		return name;
	}

	@Override
	public int getNbClient() throws RemoteException {
		return listClient.size();
	}
	
	
}
